# $Id: utils.tcl 13 2007-07-01 00:03:26Z khomoutov $
# Utility functions.

# [binary scan] wrapper that mimics the behaviour implemented in TIP#275
# thus allowing for scanning of unsigned integers.
# See http://wiki.tcl.tk/4180

if {[package vsatisfies $tcl_version 8.5]} {
	interp alias {} ::tclplkr::bscan {} binary scan
	return
}

proc ::tclplkr::bscan {data f args} {
	set c 0xFF
	set s 0xFFFF
	set S 0xFFFF
	set i 0xFFFFFFFF
	set I 0xFFFFFFFF

	set outf ""
	set upos {}
	set pos -1
	set last ?

	foreach a [split $f ""] {
		if {[string equal $a u] && [string first $last csSiI] >= 0} {
			lappend upos $pos [set $last]
		} else {
			append outf $a

			if {[string first $a aAbBhHcsSiIwWfdxX@] >= 0} {
				set last $a
				incr pos
			}
		}
	}

	set count [uplevel 1 [list binary scan $data $outf] $args]

	foreach {pos mask} $upos {
		upvar 1 [lindex $args $pos] v
		set v [expr {$v & $mask}]
	}

	set count
}

# Schelte Bron's implementation of [lassign] (appeared in Tcl 8.5)
# from http://wiki.tclers.tk/1530
# Note that Tclx also has [lassign] so we check for the existence of
# this command instead of checking the Tcl's version.
if {[info procs ::lassign] == ""} {
	proc ::lassign {values args} {
		uplevel 1 [list foreach $args [linsert $values end {}] break]
		lrange $values [llength $args] end
	}
}

